<template>
  <el-dialog
    top="30px"
    width="900px"
    title="抵押合同"
    append-to-body
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <el-form :rules="rules" ref="form" label-width="110px" :model="editData">
      <el-form-item label="抵押主体：">
        <el-button size="mini" @click="addPerson">
          <i class="fa fa-plus"></i>
          新增抵押主体
        </el-button>
        <span class="text-muted text-sm">
          资产抵押清单所有权人需与抵押主体一致，否则分开添加多个抵押合同
        </span>
        <table
          style="line-height: 1.2rem"
          class="table table-bordered table-sm table-vertical-middle text-center"
        >
          <colgroup>
            <col width="12%" />
            <col width="17%" />
            <col width="12%" />
            <col width="15%" />
            <col width="15%" />
            <col width="15%" />
            <col width="14%" />
          </colgroup>
          <tr>
            <td>类型</td>
            <td>主体名称</td>
            <td>法人</td>
            <td>联系电话</td>
            <td>证件号</td>
            <td>地址</td>
            <td>操作</td>
          </tr>
          <tr v-for="(p, index) of personData" :key="index">
            <td>{{ enumEntityType[p.com_person_type] }}</td>
            <td>{{ p.com_person_name }}</td>
            <td>{{ +p.com_person_type === 1 ? p.com_person_corp : '-' }}</td>
            <td>{{ p.com_person_phone }}</td>
            <td>{{ p.cert_no }}</td>
            <td>{{ p.com_person_address }}</td>
            <td>
              <el-button type="text" @click="addPerson(p, index)">
                <i class="fa fa-edit"></i>
              </el-button>
              <el-button type="text" @click="deletePerson(index)">
                <i class="fa fa-trash text-danger"></i>
              </el-button>
            </td>
          </tr>
          <tr v-if="!personData.length">
            <td colspan="7" class="text-muted">请先添加抵押主体</td>
          </tr>
        </table>
      </el-form-item>
      <el-form-item label="抵押物清单："></el-form-item>
      <el-form-item label="不动产">
        <el-button size="mini" @click="addHouse">
          <i class="fa fa-plus"></i>
          新增一行
        </el-button>
        <table
          style="line-height: 1.2rem"
          class="table table-bordered table-sm table-vertical-middle text-center"
        >
          <colgroup>
            <col width="13%" />
            <col width="10%" />
            <col width="11%" />
            <col width="14%" />
            <col width="15%" />
            <col width="15%" />
            <col width="16%" />
            <col width="5%" />
          </colgroup>
          <tr>
            <td>名称</td>
            <td>所有权人</td>
            <td>
              面积
              <div>（平方米）</div>
            </td>
            <td>所在地</td>
            <td>产权证号</td>
            <td>目前状况</td>
            <td>抵押期间</td>
            <td>操作</td>
          </tr>
          <tr v-for="(p, index) of houseData" :key="index">
            <td class="input-td">
              <el-input
                v-model="p.gua_pawn_name"
                placeholder="抵押物名称"
                type="textarea"
                :rows="3"
              ></el-input>
            </td>
            <td class="input-td">
              <el-input
                v-model="p.own_person"
                placeholder="姓名"
                type="textarea"
                :rows="3"
              ></el-input>
            </td>
            <td class="input-td">
              <el-input
                v-model="p.gua_pawn_scale"
                placeholder="面积"
                type="textarea"
                :rows="3"
              ></el-input>
            </td>
            <td class="input-td">
              <el-input
                v-model="p.gua_pawn_address"
                placeholder="所在地"
                type="textarea"
                :rows="3"
              ></el-input>
            </td>
            <td class="input-td">
              <el-input
                v-model="p.gua_pawn_no"
                placeholder="产权证号"
                type="textarea"
                :rows="3"
              ></el-input>
            </td>
            <td class="input-td">
              <el-input
                v-model="p.current_state"
                placeholder="目前状况"
                type="textarea"
                :rows="3"
              ></el-input>
            </td>
            <td class="input-td">
              <el-input
                v-model="p.gua_pawn_period"
                placeholder="抵押期间"
                type="textarea"
                :rows="3"
              ></el-input>
            </td>
            <td>
              <el-button type="text" class="mx-1 p-0" @click="deleteHouse(index)">
                <i class="fa fa-trash text-danger"></i>
              </el-button>
            </td>
          </tr>
        </table>
      </el-form-item>
      <el-form-item label="机动车">
        <el-button size="mini" @click="addCar">
          <i class="fa fa-plus"></i>
          新增一行
        </el-button>
        <table
          style="line-height: 1.2rem"
          class="table table-bordered table-sm table-vertical-middle text-center"
        >
          <colgroup>
            <col width="10%" />
            <col width="24%" />
            <col width="20%" />
            <col width="21%" />
            <col width="19%" />
            <col width="6%" />
          </colgroup>
          <tr>
            <td>序号</td>
            <td>机动车登记编号（牌照）</td>
            <td>机动车所有人</td>
            <td>车辆识别代号/车架号</td>
            <td>被担保债权数额</td>
            <td>操作</td>
          </tr>
          <tr v-for="(p, index) of carData" :key="index">
            <td>{{ index + 1 }}</td>
            <td class="input-td">
              <el-input v-model="p.gua_pawn_no" placeholder="牌照"></el-input>
            </td>
            <td class="input-td">
              <el-input v-model="p.own_person" placeholder="姓名"></el-input>
            </td>
            <td class="input-td">
              <el-input v-model="p.gua_pawn_name" placeholder="识别代号/车架号"></el-input>
            </td>
            <td class="input-td">
              <el-input v-model="p.gua_credit_right" placeholder="被担保债权数额"></el-input>
            </td>
            <td>
              <el-button type="text" @click="deleteCar(index)">
                <i class="fa fa-trash text-danger"></i>
              </el-button>
            </td>
          </tr>
        </table>
      </el-form-item>
      <el-form-item label="机械设备">
        <el-button size="mini" @click="addDevice">
          <i class="fa fa-plus"></i>
          新增一行
        </el-button>
        <table
          style="line-height: 1.2rem"
          class="table table-bordered table-sm table-vertical-middle text-center"
        >
          <colgroup>
            <col width="15%" />
            <col width="10%" />
            <col width="20%" />
            <col width="13%" />
            <col width="17%" />
            <col width="15%" />
            <col width="5%" />
          </colgroup>
          <tr>
            <td>名称</td>
            <td>所有权人</td>
            <td>所在地</td>
            <td>
              目前状况
              <div>（自用/租赁）</div>
            </td>
            <td>发票编号</td>
            <td>被担保债权数额</td>
            <td>操作</td>
          </tr>
          <tr v-for="(p, index) of deviceData" :key="index">
            <td class="input-td">
              <el-input v-model="p.gua_pawn_name" placeholder="抵押物名称"></el-input>
            </td>
            <td class="input-td">
              <el-input v-model="p.own_person" placeholder="姓名"></el-input>
            </td>
            <td class="input-td">
              <el-input
                v-model="p.gua_pawn_address"
                placeholder="所在地"
                type="textarea"
                :rows="2"
              ></el-input>
            </td>
            <td class="input-td">
              <c-select
                :options="enumDeviceEnum"
                :props="{
                  value: 'label',
                  label: 'label',
                }"
                v-model="p.current_state"
                placeholder="目前状况"
                clearable
              ></c-select>
            </td>
            <td class="input-td">
              <el-input v-model="p.gua_pawn_no" placeholder="发票编号"></el-input>
            </td>
            <td class="input-td">
              <el-input v-model="p.gua_credit_right" placeholder="被担保债权数额"></el-input>
            </td>
            <td>
              <el-button type="text" @click="deleteDevice(index)">
                <i class="fa fa-trash text-danger"></i>
              </el-button>
            </td>
          </tr>
        </table>
      </el-form-item>
      <el-form-item label="生物资产">
        <el-button size="mini" @click="addBiology">
          <i class="fa fa-plus"></i>
          新增一行
        </el-button>
        <table
          style="line-height: 1.2rem"
          class="table table-bordered table-sm table-vertical-middle text-center"
        >
          <colgroup>
            <col width="15%" />
            <col width="10%" />
            <col width="20%" />
            <col width="13%" />
            <col width="17%" />
            <col width="15%" />
            <col width="5%" />
          </colgroup>
          <tr>
            <td>名称</td>
            <td>所有权人</td>
            <td>所在地</td>
            <td>目前状况</td>
            <td>头数/株数</td>
            <td>被担保债权数额</td>
            <td>操作</td>
          </tr>
          <tr v-for="(p, index) of biologyData" :key="index">
            <td class="input-td">
              <el-input
                v-model="p.gua_pawn_name"
                placeholder="抵押物名称"
                type="textarea"
                :rows="2"
              ></el-input>
            </td>
            <td class="input-td">
              <el-input
                v-model="p.own_person"
                placeholder="姓名"
                type="textarea"
                :rows="2"
              ></el-input>
            </td>
            <td class="input-td">
              <el-input
                v-model="p.gua_pawn_address"
                placeholder="所在地"
                type="textarea"
                :rows="2"
              ></el-input>
            </td>
            <td class="input-td">
              <el-input
                v-model="p.current_state"
                placeholder="目前状况"
                type="textarea"
                :rows="2"
              ></el-input>
            </td>
            <td class="input-td">
              <el-input
                v-model="p.gua_pawn_scale"
                placeholder="头数/株数"
                type="textarea"
                :rows="2"
              ></el-input>
            </td>
            <td class="input-td">
              <el-input
                v-model="p.gua_credit_right"
                placeholder="被担保债权数额"
                type="textarea"
                :rows="2"
              ></el-input>
            </td>
            <td>
              <el-button type="text" @click="deleteBiology(index)">
                <i class="fa fa-trash text-danger"></i>
              </el-button>
            </td>
          </tr>
        </table>
      </el-form-item>
      <el-form-item label="合同共计" prop="num_copes_lower">
        <el-input
          class="form-control-ml"
          v-model="editData.num_copes_lower"
          placeholder="合同共计"
          v-input-number="{ min: 0, fixed: 0 }"
        >
          <span slot="append">份</span>
        </el-input>
      </el-form-item>
      <el-form-item label="甲乙双方和债务人各执" prop="num_copes_per_lower">
        <el-input
          class="form-control-ml"
          v-model="editData.num_copes_per_lower"
          placeholder="甲乙双方和债务人各执"
          v-input-number="{ min: 0, fixed: 0 }"
        >
          <span slot="append">份</span>
        </el-input>
      </el-form-item>
      <el-form-item label="是否加盖公章" v-if="isSYSTEM || isRedo">
        <c-select
          class="form-control-ml"
          :options="{
            0: '不盖章(客户线下签约时选择)',
            1: '加盖公章',
          }"
          :number-key="true"
          v-model="signStatus"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button class="btn-long" type="primary" @click="submit" :loading="saveLoading">
          保存
        </el-button>
        <el-button class="btn-long" @click="beforeClose" :loading="saveLoading">取消</el-button>
      </el-form-item>
    </el-form>

    <mortgage-add
      :visible.sync="addVisible"
      :form-data="addData"
      :attach="addAttach"
      @back="setPerson"
    ></mortgage-add>
  </el-dialog>
</template>

<script>
import { enumEntityType } from '@/credit/views/county/unionProvince/components/ContractGuardMortgage'
import { nzhToNum, arrayFromString, arrayToString } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
import { uploadOss, deleteOss } from '@/common/api/oss'
import MortgageAdd from '@/credit/views/county/unionProvince/components/contractApproveDeploy/mortgage/MortgageAdd'
export default {
  components: {
    MortgageAdd,
  },
  props: {
    visible: Boolean,
    isRedo: {
      // 是否合同重做，
      type: Boolean,
      default: false,
    },
    tableId: { type: String, default: '' },
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      enumEntityType,
      enumDeviceEnum: [{ label: '自用' }, { label: '租赁' }],
      editData: {},
      rules: {
        num_copes_lower: { required: true, message: '请输入合同份数', trigger: 'blur' },
        num_copes_per_lower: { required: true, message: '请输入合同份数', trigger: 'blur' },
      },
      tableName: 'gua_contract',
      saveLoading: false,
      houseData: [{}],
      carData: [{}],
      deviceData: [{}],
      biologyData: [{}],
      personData: [],
      tableListName: 'gua_pawn_list',

      addAttach: [],
      editIndex: -1,
      addVisible: false,
      addData: {},
      deleteAttach: [],
      signStatus: 1,
    }
  },
  computed: {
    ...mapGetters(['entrustContract', 'org']),
    queryId() {
      return this.relatedData.customer_related_id
    },
    isSYSTEM() {
      // 系统后台重做合同
      return this.org.orgClass === 'org_credit_sys'
    },
  },
  watch: {
    formData: {
      handler: function () {
        this.editData = { ...this.formData }
        this.getData()
        this.getPerson()
      },
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    setPerson(person) {
      if (this.editIndex === -1) {
        this.personData.push(person)
      } else {
        this.personData[this.editIndex] = { ...person }
      }
    },
    addPerson(row = {}, index = -1) {
      if (index !== -1) {
        const attach = arrayFromString(row.cert_attachment)
        this.addAttach = row.url ? [{ url: row.url }] : [{ url: attach?.[0] ?? '' }]
      } else {
        this.addAttach = []
      }
      this.editIndex = index
      this.addVisible = true
      this.addData = { ...row }
    },
    getPerson() {
      this.personData = []
      if (!this.tableId) {
        return
      }
      this.saveLoading = true
      this.$api
        .getData(
          this.$serviceName,
          'com_person_gua_list',
          {
            'gua_contract_id.eq': this.tableId,
          },
          { create_time: 'asc' }
        )
        .then(res => {
          this.personData = res?.data ?? []
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    getData() {
      this.houseData = []
      this.carData = []
      this.deviceData = []
      this.biologyData = []
      if (!this.tableId) {
        return
      }
      this.saveLoading = true
      this.$api
        .getData(
          this.$serviceName,
          this.tableListName,
          {
            'gua_contract_id.eq': this.tableId,
          },
          { create_time: 'asc' }
        )
        .then(res => {
          const data = res?.data ?? []
          this.houseData = data.filter(item => +item.gua_pawn_type === 1) || []
          this.carData = data.filter(item => +item.gua_pawn_type === 2) || []
          this.deviceData = data.filter(item => +item.gua_pawn_type === 3) || []
          this.biologyData = data.filter(item => +item.gua_pawn_type === 4) || []
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    addHouse() {
      this.houseData.push({})
    },
    addCar() {
      this.carData.push({})
    },
    addDevice() {
      this.deviceData.push({})
    },
    addBiology() {
      this.biologyData.push({})
    },
    deleteBiology(index) {
      this.biologyData.splice(index, 1)
    },
    deletePerson(index) {
      const deleteData = this.personData.splice(index, 1)
      const data = deleteData?.[0] ?? {}
      if (data.cert_attachment) {
        const attach = arrayFromString(data.cert_attachment)
        this.deleteAttach.push(...attach)
      }
      if (data.url) {
        URL.revokeObjectURL(data.url)
      }
    },
    deleteHouse(index) {
      this.houseData.splice(index, 1)
    },
    deleteCar(index) {
      this.carData.splice(index, 1)
    },
    deleteDevice(index) {
      this.deviceData.splice(index, 1)
    },
    handleBeforeSave(model) {
      model.customer_name = this.relatedData.customer_name
      model.customer_address = this.relatedData.address
      model.customer_phone = this.relatedData.mobile_no
      model.bank_name = this.entrustContract.bank_name
      model.entrust_bank_name = this.entrustContract.entrust_bank_name
      model.apply_funds = this.entrustContract.reply_funds
      model.loan_contract_no = this.entrustContract.loan_contract_no
      model.ensure_contract_no = this.entrustContract.ensure_contract_no
      // model.ensure_contract_name = this.entrustContract.ensure_contract_name
      model.gua_com_corp = this.entrustContract.accept_entrust_entity_corp
      model.sign_date = this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日')
      model.num_copes_per = model.num_copes_per_lower ? nzhToNum(model.num_copes_per_lower) : ''
      model.num_copes = model.num_copes_lower ? nzhToNum(model.num_copes_lower) : ''
      model.customer_related_id = this.queryId
      model.gua_method = 3
      return model
    },
    handleUploadFile() {
      const promises = this.personData.map(item => {
        const attach = item.cert_attachment ? arrayFromString(item.cert_attachment) : ''
        if (item.file) {
          if (attach) {
            this.deleteAttach.push(...attach)
          }
          return uploadOss({
            file: item.file,
            dir: `credit/contract/mortgage/${this.queryId}/`,
            type: 0,
          })
        } else {
          return Promise.resolve(attach?.[0] || '')
        }
      })
      return Promise.all(promises)
        .then(list => {
          list.forEach((attachment, index) => {
            const { file, url, ...data } = this.personData[index]
            data.cert_attachment = attachment ? arrayToString([attachment]) : arrayToString([])
            this.personData[index] = data
          })
          this.editData.cert_attachment = arrayToString(list.filter(item => item))
        })
        .finally(() => {
          deleteOss(this.deleteAttach)
        })
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const guaData = [
            ...this.houseData,
            ...this.carData,
            ...this.deviceData,
            ...this.biologyData,
          ]
          if (!guaData.filter(item => item.gua_pawn_name).length) {
            return this.$message.error('至少输入一个抵押物')
          }
          this.saveLoading = true
          this.handleUploadFile().finally(() => {
            this.saveLoading = false
            this.personData = this.personData.map(item => {
              const { file, url, ...data } = item
              return data
            })
            this.putData()
          })
        } else {
          this.$message.error('输入错误，请重新输入！')
        }
      })
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    putData() {
      if (!this.queryId) {
        return
      }
      let slaveData = []
      let personData = this.personData
      if (personData.length < 1) {
        return this.$message.warning('至少填入一个抵押主体')
      }
      this.editData.is_com_person_gua = personData.length > 1 ? 1 : 0
      this.editData.gua_entity_type = personData.length > 1 ? '' : personData[0].com_person_type
      this.editData.gua_entity = personData.map(item => item.com_person_name).join('、')
      this.editData.gua_entity_mobile = personData.map(item => item.com_person_phone).join('、')
      this.editData.gua_entity_cert_no = personData.map(item => item.cert_no).join('、')
      this.editData.gua_entity_address = personData.map(item => item.com_person_address).join('、')
      for (let p of this.houseData) {
        if (p.gua_pawn_name) {
          slaveData.push({ ...p, gua_pawn_type: 1, gua_credit_right: '' })
        }
      }
      for (let i = 0; i < this.carData.length; i++) {
        if (this.carData[i].gua_pawn_no) {
          slaveData.push({ ...this.carData[i], gua_pawn_type: 2 })
        }
      }
      for (let p of this.deviceData) {
        if (p.gua_pawn_name) {
          slaveData.push({ ...p, gua_pawn_type: 3 })
        }
      }
      for (let p of this.biologyData) {
        if (p.gua_pawn_name) {
          slaveData.push({ ...p, gua_pawn_type: 4 })
        }
      }
      if (!slaveData.length) {
        return this.$message.error('至少输入一个抵押物')
      }
      this.saveLoading = true
      const data = this.handleBeforeSave(this.editData)
      if (this.isSYSTEM || this.isRedo) {
        //系统后台重做重签合同
        data.sign_status = this.signStatus
        data.re_sign_type = this.tableId ? 1 : 2
      }

      if (this.tableId) {
        data.gua_contract_id = this.tableId
        slaveData = slaveData.map(item => {
          item.gua_contract_id = this.tableId
          return item
        })
        personData = personData.map(item => {
          item.gua_contract_id = this.tableId
          return item
        })
      }

      const formData = {
        masterTableInfo: JSON.stringify(data),
        masterTableName: this.tableName,
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: this.tableListName,
        slaveTableName1: 'com_person_gua_list',
        slaveTableInfo1: JSON.stringify(personData),
      }
      if (this.tableId) {
        this.saveLoading = true
        this.$api
          .relatedUpdate(this.$serviceName, formData)
          .then(() => {
            this.beforeClose()
            this.$emit('success', true)
            this.$message.success('保存成功')
          })
          .catch(err => {
            this.$message.error(err?.data?.error_description || '提交失败，请重试！')
          })
          .finally(() => {
            this.saveLoading = false
          })
      } else {
        this.saveLoading = true
        this.$api
          .relatedBatch(this.$serviceName, formData)
          .then(() => {
            this.beforeClose()
            this.$emit('success', true)
            this.$message.success('保存成功')
          })
          .catch(err => {
            this.$message.error(err?.data?.error_description || '提交失败，请重试！')
          })
          .finally(() => {
            this.saveLoading = false
          })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.input-td {
  background: #ffffee;
}
</style>
